package fudan.se.project.service.infrastructure.func.conference.action.author;


import fudan.se.project.controller.request.PaperSubmitRequest;
import fudan.se.project.domain.conference.Topic;
import fudan.se.project.domain.conference.production.Paper;
import fudan.se.project.domain.conference.production.Writer;
import fudan.se.project.service.infrastructure.entity.conference.TopicService;
import fudan.se.project.service.infrastructure.entity.conference.production.PaperService;
import fudan.se.project.service.infrastructure.entity.conference.production.WriterService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashSet;
import java.util.List;

@Service
public class PaperUpdateService {
    PaperService paperService;
    WriterService writerService;
    TopicService topicService;

    public PaperUpdateService(PaperService paperService,
                              WriterService writerService,
                              TopicService topicService
    ) {
        this.paperService = paperService;
        this.writerService = writerService;
        this.topicService = topicService;
    }

    public boolean process(PaperSubmitRequest request, Paper paper, MultipartFile file) {

        HashSet<Topic> topicHashSet = new HashSet<>();

        for (Long id : request.getTopicIds()) {
            Topic topic;
            if ((topic = topicService.findById(id)) == null) {
                return false;
            } else {
                topicHashSet.add(topic);
            }
        }

        if (!paperService.deletePaperFile(paper)||
                !paperService.store(paper.getConference().getId(), paper.getId(), file)
        ) {
            return false;
        }


        writerService.deleteAllByPaper(paper);

        paper.setTitleText(request.getTitleText());
        paper.setAbstractText(request.getAbstractText());
        paper.setOriginalFilename(file.getOriginalFilename());
        paper.setTopics(topicHashSet);
        paper.getWriters().clear();

        paper = paperService.save(paper);

        int index = 0;
        List<Writer> writerList = request.getWriters();
        for (Writer writer : writerList) {
            writer.setPaper(paper);
            writer.setIndex(index++);
        }
        writerService.saveAll(writerList);

        return true;

    }


}
